package com.hys.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.hys.exception.ServiceException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileDownUtil {


    /**
     * 下载临时文件（下载之后删除文件）
     * @param delTemplate
     * @param file
     * @param fileName
     */
    public static void downTemporaryFile( String delTemplate, File file, String fileName) {

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
        try ( InputStream inputStream = new FileInputStream(file);
              OutputStream outputStream = response.getOutputStream() ) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=UTF-8''" +
                    URLUtil.encode(fileName));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();

        } catch (Exception e) {
            throw new ServiceException("文件下载异常！");
        } finally {
            FileUtil.del(new File(delTemplate));
        }
    }

}
